$import("biz.base.FormEditorUtil"); 

(function(exports){
	function TreeFormPanel(c){
		var me=this,initialConfig=c;
		Ext.applyIf(me,c);
	}
	var pt=TreeFormPanel.prototype;
	pt={
			initCptConfig:function(){
				var me=this;
				this.dataUrl='./meta/dataTree?rankId='+me.id;
			},
			initTreeConfig:function(region){
				var me=this,ctrlId=this.treecptId,
				treeLoader = new Ext.tree.TreeLoader({
					dataUrl :me.dataUrl,
					nodeParameter:"id"
				});
				this.treeConfig={
						id : ctrlId,
						split : true,
						region : region,
						autoScroll : true,
						width : 350,
						enableDD:true,
						animate : true,
						floatable : false,
						titleCollapse : true,
						rootVisible : false,
						lines : false,
						useArrows : true,
						loader : treeLoader,
						root : new Ext.tree.AsyncTreeNode({
							id : me.rootId,
							text : '根节点'
						}),
						tbar:[{
							iconCls:'icon-create',
							tooltip:{text:'新建'},
							text:'新建',
							handler:function(){
								var metaTree=Ext.getCmp(ctrlId);
								var cur_node=metaTree["cur_node"];
								var win=getNewMenuWin();
								win.show();
							}
						},{
							text:'删除',
							iconCls:'icon-delete',
							handler:function(){
								var metaTree=Ext.getCmp(ctrlId);
								if(!metaTree["cur_node"]){
									return Ext.Msg.alert('提示','请选择要删除的节点');
								}
								Ext.Msg.confirm('提示',"确认删除此项(确保无子节点)?",function(txt){
									if(txt=='no')return;
									
									var pNode=metaTree["cur_node"].parentNode;
									var url="./delete/"+metaTree["cur_node"].id;
									doHttpGet(url);
									pNode.reload();
								});
							}
						},{
							text:'刷新',
							iconCls:'icon-reload',
							handler:function(){
								var metaTree=Ext.getCmp(ctrlId);
								metaTree.getRootNode().reload();
								window.parent.reloadMenu();
							}
						}],
						listeners:{
							'click':function(n){
								metaTree["cur_node"]=n;
								var detailForm=me.detailForm;
								detailForm["loadData"](n);
							},
							'movenode':function(tree,node,oldParent,newParent,index){
								var url=getContextBase()+"meta/move";
								Ext.Ajax.request( {
										url : url,
										method : 'post',
										params : {
											id:node.id,
											fid:newParent.id,
											seq:index,
											rankId:rankId
										},
										success: function() { 
											oldParent.reload();
											if(oldParent!=newParent)
												newParent.reload();
						                },
						                failure: function() {  
						                	oldParent.reload();
											if(oldParent!=newParent)
												newParent.reload();
						                }  
								    });
							}
						}
					};
			},
			initTree:function(region){
			var me=this,config=initTreeConfig(region),
			metaTree =this.treePanel=new Ext.tree.TreePanel();
			return metaTree;
		},
		getFieldByMeta:function(field){
			var attr={},attrs = field["attrs"];
			if(attrs.required){attr.allowBlank=true;}
			Ext.applyIf(attr,field);
			delete attr["attrs"];
			var fld= FormEditorUtil.get(field['type'],attr);
			if( fld.fieldLabel && fld.allowBlank===false ){
				fld.fieldLabel += '<font color=red>*</font>';
			}
			return fld;
		},
		getEditFormFields:function(){
			var me=this,fields=me["fields"],fs=[];
			Ext.each(fields,function(field,i){
				var fld=me.getFieldByMeta(field);
				fs.push(fld);
			});
			return fs;
		},
		initDetailForm:function(region){
			var me=this,form =this.detailForm= new Ext.FormPanel({
		        frame: true,
		        labelAlign: 'right',
		        labelWidth: 85,
		        split:true,
		        height:220,
		        scrollable:true,
		        autoScroll:true,
		        title:'详细信息',
		        region:region,
		        id:'detailForm',
		        closable:true,
		        waitMsgTarget: true,
		        defaults:{
		        	xtype:'textfield',
		        	width:220
		        },
		        items:me.getEditFormFields() ,
		        buttons:[{
		        text:'更新',
		        handler:function(b){
		        	var detailForm=Ext.getCmp('detailForm');
		        	var node=detailForm["cur_node"];
		        	if(!node)return;
		       	 var form=detailForm.getForm();
		       	b.setDisabled(true);
		       	
		       	var url="./update/menu";
		       	form.submit({
					submitEmptyText: false,
		  		    clientValidation: true,
		  		    url: url,
		  		    success: function(form, action) {
		  		    	b.setDisabled(false);
		  		    	reload(node.fid);
		  		    	Ext.Msg.alert('提示', '更新成功！');
		     		},
		  		    failure: function(form, action) {
		  		    	b.setDisabled(false);
		  		    	reload(node.fid);
		  		    	Ext.Msg.alert('提示', "更新失败");
		  		    }
		       	});
		        }
		    },{
		        text: '重置',
		        handler: function(){
		        	var form=Ext.getCmp('detailForm').getForm();
		          	 var textCtrl=form.findField("text");
		          	textCtrl.setValue(textCtrl.originalValue);
		          	 var flagCtrl=form.findField("flag");
		          	flagCtrl.setValue(flagCtrl.originalValue);
		          	 var urlCtrl=form.findField("url");
		          	 urlCtrl.setValue(urlCtrl.originalValue);
		        }
		    }]
		 });
			form["loadData"]=function(node){
				var attrs=node.attributes;
				form["cur_node"]=node.attributes;
				var detailForm=form.getForm();
				detailForm.items.each(function(item,index,length){
					var name=item.name;
					item.setValue(attrs[name]);
				});
			};
			return form;
		},
		showAddNodeWin:function(){
			
		},
		doReload:function(id){
			
		},
		doDeleteNode:function(){
			
		},
		display:function(){
			var me=this;
			Ext.onReady(function() {
				Ext.QuickTips.init();
				var tree=me.initTree('west');
				var detailForm=me.initDetailForm('center');
				new Ext.Viewport({
					layout : 'border',
					items : [tree, detailForm]
				});
			});
		}
	};
	exports.TreeFormPanel=TreeFormPanel;
})(window);



function getNewMenuWin(){
	var win=Ext.getCmp('menuFolderWin');
	 if(win)return win;
	 var form = new Ext.FormPanel({
	        frame: true,
	        labelAlign: 'right',
	        labelWidth: 85,
	        width:150,
	        id:'menuFolderForm',
	        closable:true,
	        waitMsgTarget: true,
	        items: [
	                {name: 'map.fid',xtype:'textfield',hidden:true},
	                {	fieldLabel: '名称',
	                	name: 'map.name',
	                	allowBlank:false,
	                	editable:false,
	                	width:190,
	                	xtype:'textfield'
	                },{	fieldLabel: '说明',
	                	name: 'map.text',
	                	allowBlank:false,
	                	editable:false,
	                	width:190,
	                	xtype:'textfield'
	                },{
	                	fieldLabel:"类型",
	                	name:"map.meta"
	                }],
	        buttons:[{
            text:'提交',
            handler:function(){
            	var menu_tree=Ext.getCmp('menu_tree');
           	 var curNode=menu_tree["cur_node"];
           	 var form=Ext.getCmp('menuFolderForm').getForm();
           	 var fidCtrl=form.findField("fid");
           	 if(!curNode){
           		 fidCtrl.setValue(menu_tree.getRootNode().id);
           	 }else{
           		 var attrs=curNode.attributes;
           		 fidCtrl.setValue(attrs.id);
           	 }
            	var conf={
	  	   	  		    clientValidation: true,
	  	   	  		    url: "./add",
	  	   	  		    waitMsg:"保存中，请稍后...",
	  	   	  		    success: function(form, action) {
	  	   		  		  	var menu_tree=Ext.getCmp('menu_tree');
	  	   		  		  	var fidCtrl=form.findField("fid");
	  	   		  			if(!curNode){
	  	   		  				fidCtrl.setValue(menu_tree.getRootNode().id);
	  	   		  			}else{
	  	   		  			var attrs=curNode.attributes;
	  	   		  			fidCtrl.setValue(attrs.id);
	  	   		  			}
	  	   		  		  	menu_tree.getNodeById(fidCtrl.getValue()*1).reload();
	  	   		  		  	var win=Ext.getCmp('menuFolderWin');
	  	   		  		  	win.hide();
	  	   	     		},
	  	   	  		    failure: function(form, action) {
	  	   	  		 		return Ext.Msg.alert("结果","创建失败");
	  	   	  		    	var win=Ext.getCmp('menuFolderWin');
	  	   	  		    	win.hide();
	  	   	  		    }
	  	   	  		};
	  	    	form.submit(conf);
            }
        },{
            text: '取消',
            handler: function(){
            	var win=Ext.getCmp('menuFolderWin');
            	win.hide();
            }
        }]
	 });
	 var win = new Ext.Window({
        layout:'fit',
        id:"menuFolderWin",
        modal:true,
        title:'创建',
        width:320,
        height:140,
        plain: true,
        items: form
    });
	 return win;
}

function getIconPicker(id){
	var win=Ext.getCmp(id);
	if(!win){
		var url="../ui/icon/layui_icon_picker.html";
		win=new Ext.Window({
			frame:true,
	        plain:true,
	        id:id,
	        width:580,
	        height:400,
	        resizable:true,
	        buttonAlign:"right",
	        maximizable:true,
	        closable:true,
	        html:"<iframe frameborder=0 src='"+url+"' width=100% height=100%/>"
		})
	}
	win.show();
	
}
function setIconCls(iconCls){
	Ext.getCmp('detailForm').getForm().findField("iconCls").setValue(iconCls);
	Ext.getCmp('icon_selector').hide();
}
